package manage;

import entity.FlightInfo;
import entity.HotelInfo;
import entity.OrderInfo;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

public class OrderDBManager {
    public static void addOrder(String username, String orderDate, String orderType, String orderName, int number) {
        DBManager dbManager = new DBManager();
        dbManager.establishConnection();
        String query = "insert into ORDER_T(username, orderDate, orderType, orderName, number) values('" + username + "','" + orderDate + "','" + orderType + "','" + orderName + "'," + number + ")";
        dbManager.updateDB(query);
        dbManager.closeConnections();
    }

    public static void cancelOrder(OrderInfo orderInfo) {
        DBManager dbManager = new DBManager();
        dbManager.establishConnection();
        String query = "DELETE FROM ORDER_T WHERE id = " + orderInfo.getId();
        dbManager.updateDB(query);
        if (orderInfo.getOrderType().equals("FLIGHT")) {
            FlightDBManager.updateFlightSeat(new FlightInfo(orderInfo.getOrderName()), orderInfo.getNumber());
        } else {
            HotelDBManager.updateHotelTable(new HotelInfo(orderInfo.getOrderName()), orderInfo.getNumber());
        }
        dbManager.closeConnections();
    }

    public static ArrayList<OrderInfo> getOrders(String name) {
        ResultSet rs;
        ArrayList<OrderInfo> ret = new ArrayList<OrderInfo>();
        try {
            DBManager dbManager = new DBManager();
            rs = dbManager.queryDB("SELECT * FROM ORDER_T WHERE USERNAME='" + name + "'");
            while (rs.next()) {
                String username = rs.getString("USERNAME");
                Date orderdate = rs.getDate("ORDERDATE");
                String orderType = rs.getString("ORDERTYPE");
                String orderName = rs.getString("ORDERNAME");
                int id = rs.getInt("ID");
                int number = rs.getInt("NUMBER");
                double price;
                if (Objects.equals(orderType, "HOTEL")) {
                    ResultSet resultSet = dbManager.queryDB("SELECT h.price FROM HOTEL_T h JOIN ORDER_T o ON h.NAME=o.orderName WHERE h.NAME='" + orderName + "'");
                    resultSet.next();
                    price = resultSet.getDouble("PRICE");
                } else {
                    ResultSet resultSet = dbManager.queryDB("SELECT f.price FROM FLIGHT_T f JOIN ORDER_T o ON f.NAME=o.orderName WHERE f.NAME='" + orderName + "'");
                    resultSet.next();
                    price = resultSet.getDouble("PRICE");
                }
                ret.add(new OrderInfo(username, orderdate, orderType, orderName, id, price, number));
            }
            rs.close();
            dbManager.closeConnections();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ret;
    }

}
